<template>
  <div class="emrChart-container">
    <div class="el-descriptions__header">
      <div class="el-descriptions__title">关键体征趋势</div>
    </div>
    <el-menu
      :default-active="activeIndex"
      mode="horizontal"
      @select="handleSelect"
    >
      <el-menu-item index="1">体温</el-menu-item>
      <el-menu-item index="2">脉搏</el-menu-item>
      <el-menu-item index="3">呼吸</el-menu-item>
      <el-menu-item index="4">体重</el-menu-item>
      <el-menu-item index="5">身高</el-menu-item>
      <el-menu-item index="6">血压</el-menu-item>
    </el-menu>
    <div class="emrChart-content">
      <div class="hubs">
        <el-radio-group v-model="radioActive" @change="chartTypeChange">
          <el-radio-button label="列表"></el-radio-button>
          <el-radio-button label="图表"></el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="record">记录</el-button>
      </div>
      <template v-if="radioActive === '列表'">
        <el-table
          :data="pageData.listData"
          :header-cell-style="{ background: '#F5F5F5', 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <XMTableColumn prop="fillingTime" label="时间"></XMTableColumn>
          <XMTableColumn prop="value" :label="getValueName()"></XMTableColumn>
          <XMTableColumn label="操作">
            <template #default="scope">
              <el-button size="small" type="text" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-button
                size="small"
                type="text"
                style="color: #f56c6c"
                @click="del(scope.row)"
              >
                删除
              </el-button>
            </template>
          </XMTableColumn>
        </el-table>
        <xm-pagination
          :total="pageData.total"
          @pagination="paginaChange"
        ></xm-pagination>
      </template>
      <div v-else style="width: 100%; height: 300px; text-align: center">
        <xm-line-chart
          v-if="pageData.chartData"
          :chartData="pageData.chartData"
          :legendData="legendData"
        ></xm-line-chart>
        <div style="color: #909399; line-height: 60px">暂无数据</div>
      </div>
    </div>
    <el-dialog
      width="30%"
      :title="getDialog()"
      v-model="isVisble"
      @closed="() => dialogRef.resetFields()"
    >
      <el-form
        label-width="140px"
        :rules="rules"
        :model="pageData.form"
        ref="dialogRef"
      >
        <xm-f-picker
          type="datetime"
          disabledDateT="after"
          v-model="pageData.form.fillingTime"
          label="测量时间："
          prop="fillingTime"
        ></xm-f-picker>
        <el-form-item :label="getValueName('table1') + '：'" prop="startValue">
          <el-input v-model="pageData.form.startValue"></el-input>
        </el-form-item>
        <el-form-item
          v-if="activeIndex === '6'"
          :label="getValueName('table2') + '：'"
          prop="endValue"
        >
          <el-input v-model="pageData.form.endValue"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isVisble = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import { reactive, ref } from '@vue/reactivity'
  import { XmPagination, XmLineChart, XmFPicker } from 'XMC/index'
  import {
    queryPage,
    addPatientSign,
    dayLastRecord,
    delSigns,
  } from '@/api/modules/patient' //
  import { onMounted } from '@vue/runtime-core'
  import { ElMessage, ElLoading } from 'element-plus'
  import { useStore } from 'vuex'
  import moment from 'moment'
  export default {
    name: 'emrChart',
    components: { XmLineChart, XmPagination, XmFPicker },
    props: { id: Number },
    setup(props) {
      const activeIndex = ref('1')
      const radioActive = ref('列表')
      let isVisble = ref(false)
      const legendData = ref(['体温(℃)'])
      const pageData = reactive({
        listData: [],
        total: null,
        search: {
          patientId: props.id,
          pageIndex: 1,
          pageSize: 5,
          type: activeIndex.value,
        },
        form: { fillingTime: '', startValue: null, endValue: null },
        chartData: null,
      })
      const record = function () {
        pageData.form = { fillingTime: '', startValue: null, endValue: null }
        isVisble.value = true
      }

      const loadData = async function (params) {
        const res = await queryPage(params)
        pageData.listData = res.data.map((item) => {
          item.value = item.startValue

          if (params.type === '6') {
            item.value = item.startValue + '~' + item.endValue
          }
          item.fillingTime = moment(item.fillingTime).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          return item
        })
        pageData.total = res.total
      }

      // 表格数据
      const chartTypeChange = function (label) {
        console.log('chartTypeChange =' + label)
        if (label === '列表') {
          loadData(pageData.search)
        } else {
          loadDLRecord(pageData.search)
        }
      }
      const edit = function (row) {
        console.log('row =' + JSON.stringify(row))
        pageData.form = {
          fillingTime: row.fillingTime,
          startValue: row.startValue,
          endValue: row.endValue,
          id: row.id,
        }
        isVisble.value = true
      }
      const del = async function (row) {
        await delSigns({ id: row.id })
        loadData(pageData.search)
        ElMessage.success('删除成功')
      }
      const loadDLRecord = async function (params) {
        const res = await dayLastRecord(params)
        let xAxis = [],
          startValue = [],
          endValue = []
        res.data.forEach((item) => {
          xAxis.push(moment(item.patientSignsDto.fillingTime).format('MM-DD'))
          startValue.push(item.patientSignsDto.startValue)
          if (params.type === '6') endValue.push(item.patientSignsDto.endValue)
        })
        pageData.chartData = null
        if (startValue.length > 0)
          pageData.chartData = { xAxis, startValue, endValue }
      }
      onMounted(() => {
        loadData(pageData.search)
      })
      const handleSelect = function (key) {
        activeIndex.value = key
        pageData.search.type = key
        radioActive.value = '列表'
        const dict = {
          1: ['体温(℃)'],
          2: ['脉搏(次/min)'],
          3: ['呼吸(次/min)'],
          4: ['体重(kg)'],
          5: ['身高(cm)'],
          6: ['舒张压(mmHg)', '收缩压(mmHg)'],
        }
        legendData.value = dict[key]

        loadData(pageData.search)
      }
      const paginaChange = function (params) {
        pageData.search.pageIndex = params.current
        pageData.search.pageSize = params.pageSize
        pageData.search.orderType = params.orderType
        loadData(pageData.search)
      }
      const getValueName = function (type) {
        const item = [
          '',
          '体温(℃)',
          '脉搏(次/min)',
          '呼吸(次/min)',
          '体重(kg)',
          '身高(cm)',
          '血压(mmHg)(收缩压～舒张压)',
        ]
        if (type && pageData.search.type > 5) {
          return type === 'table1' ? '舒张压(mmHg)' : '收缩压(mmHg)'
        }
        return item[pageData.search.type]
      }

      // 弹窗相关
      const getDialog = function () {
        const item = ['', '体温', '脉搏', '呼吸', '体重', '身高', '血压']
        return item[pageData.search.type] + '记录'
      }

      const store = useStore()
      const onSubmit = async function () {
        dialogRef.value.validate(async (valid) => {
          if (valid) {
            pageData.form['type'] = pageData.search.type
            pageData.form['patientId'] = props.id
            const loading = ElLoading.service()
            const res = await addPatientSign(pageData.form).catch(() => {
              loading.close()
            })
            isVisble.value = false
            loading.close()
            // 刷新图表
            chartTypeChange(radioActive.value)
            pageData.form = {
              fillingTime: null,
              startValue: null,
              endValue: null,
            }
            ElMessage.success(res.message)
            store.dispatch('patient/loadPatientInfo', props.id)
          }
        })
      }
      const valF = function (rule, value, cb) {
        console.log('valF = ' + JSON.stringify(value))
        let patten = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g
        if (patten.test(value)) {
          return true
        } else {
          return cb('必须为数字或小数')
        }
      }
      const rules = {
        fillingTime: [
          { required: true, trigger: 'input', message: '请选择时间' },
        ],
        startValue: [{ required: true, validator: valF, trigger: 'input' }],
        endValue: [{ required: true, validator: valF, trigger: 'input' }],
      }
      const dialogRef = ref(null)
      return {
        activeIndex,
        radioActive,
        isVisble,
        record,
        handleSelect,
        paginaChange,
        getValueName,
        onSubmit,
        pageData,
        chartTypeChange,
        getDialog,
        edit,
        del,
        rules,
        dialogRef,
        legendData,
      }
    },
  }
</script>
<style lang="scss" scoped>
  .emrChart-container {
    .el-descriptions__header {
      height: 40px;
      margin-bottom: 0px;
    }

    .el-menu-item {
      height: 40px;
      line-height: 40px;
    }

    .emrChart-content {
      margin-top: 20px;
      padding: 0 20px;
      overflow: hidden;

      .hubs {
        margin-bottom: 20px;

        .el-button {
          vertical-align: middle;
          float: right;
        }
      }
    }
  }
</style>
